package com.ugoodtech.mdcc.client.controller;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.dto.AllDepartmentListVO;
import com.ugoodtech.mdcc.client.dto.DeparmentDTO;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.dto.ServerResponse;
import com.ugoodtech.mdcc.client.service.DepartmentService;
import com.ugoodtech.mdcc.client.service.GetDeparmentUserService;
import com.ugoodtech.mdcc.core.domain.Department;
import com.ugoodtech.mdcc.core.domain.QDepartment;
import com.ugoodtech.mdcc.core.domain.User;
import com.ugoodtech.mdcc.core.repository.DepartmentRepository;
import com.ugoodtech.mdcc.core.repository.UserRepository;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

@Api(description = "部门相关接口")
@RestController
@RequestMapping("/deparment")
public class DeparmentUserController extends BaseController{

    @Autowired
    private GetDeparmentUserService getDeparmentUserService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private DepartmentService departmentService;

    @ApiOperation("获取部门列表")
    @RequestMapping(value = "getParent", method = RequestMethod.GET)
    public JsonResponse getDeparment(Principal principal) {
//        User clientUser = userRepository.findByUsername(principal.getName());
//        if (clientUser == null) {
//            return JsonResponse.errorResponseWithError("500", "未找到此用户");
//        }
        return getDeparmentUserService.getSuperDeparment();
    }


    @ApiOperation("获取部门列表")
    @RequestMapping(value = "getChild", method = RequestMethod.GET)
    public JsonResponse getChildrenDeparment(Principal principal,
                                             @ApiParam("父类部门ID") @RequestParam(value = "parentId") Long parentId,
                                             @ApiParam("父类部门ID") @RequestParam(value = "name", required = false) String name) {
//        User clientUser = userRepository.findByUsername(principal.getName());
//        if (clientUser == null) {
//            return JsonResponse.errorResponseWithError("500", "未找到此用户");
//        }
        return getDeparmentUserService.getChildrenDeparment(parentId, name);
    }

    @ApiOperation("获取指定的部门负责人")
    @RequestMapping(value = "getReportPointUser", method = RequestMethod.GET)
    public JsonResponse getReportPointUser(Principal principal,
                                           @ApiParam("报告ID") @RequestParam(value = "reportId") Long reportId,
                                           @ApiParam("指定的部门负责人") @RequestParam(value = "userIds") String userIds) {
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("500", "未找到此用户");
        }
        return getDeparmentUserService.getReportPointUser(reportId, userIds);
    }
    /**
     *This URL is used for getting the "所属部门" list for adding staff
     */
    @RequestMapping(value = "/getAllDepartmentsList", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse getAllDepartmentsList(@RequestParam(value = "departmentType",required = false, defaultValue = "0") Integer departmentType,
                                                @RequestParam(value = "departmentName",required = false) String departmentName) throws Exception{
        User currentUser = getCurrentUser();
        List<AllDepartmentListVO> allDepartmentListVoList = departmentService.getAllDepartmentsList(departmentType, departmentName,currentUser);
        return ServerResponse.success("获取所有部门列表成功",allDepartmentListVoList);
    }
    @ApiOperation("部门列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "data", response = User.class)
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = false, paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getAllDepartment(@ApiParam("用户ID") @RequestParam(value = "userId", required = false) Long userId,
                                         @ApiParam("姓名") @RequestParam(value = "username", required = false) String username,
                                         @ApiParam("意见内容") @RequestParam(value = "description", required = false) String suggestion,
                                         Pageable pageable) {
        List<Department> departments = getDeparmentUserService.getFirstDepartments();
        for (Department department : departments) {
            setChildren(department);
        }

        return JsonResponse.successResponseWithData(departments);
    }

    public void setChildren(Department department) {
        List<Department> children = getDeparmentUserService.getChildDepartments(department.getId());
        department.setChildren(children);
        for (Department cDepartment : children) {
            setChildren(cDepartment);
        }
    }

    @ApiOperation("部门下拉框")
    @ApiResponses({
            @ApiResponse(code = 200, message = "data", response = User.class)
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = false, paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "/comboList", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse comboList(@ApiParam("指定的部门") @RequestParam(value = "userIds", required = false) String userIds,
                                  @ApiParam("报告Id") @RequestParam(value = "reportId", required = false) Long reportId,
                                  @ApiParam("部门关键字") @RequestParam(value = "deparmentNameKey", required = false) String deparmentNameKey,
                                  Pageable pageable) {
        if (StringUtils.isNotEmpty(deparmentNameKey)) {
            QDepartment qDepartment = QDepartment.department;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qDepartment.deleted.eq(false));
            builder.and(qDepartment.enabled.eq(true));
            builder.and(qDepartment.name.like("%" + deparmentNameKey + "%"));
            List<Department> page = (List<Department>) departmentRepository.findAll(builder);
            List<DeparmentDTO> comboData = new ArrayList<>();
            for (Department department : page) {
                Long learderId = null;
                if (department.getLeader() != null) {
                    learderId = department.getLeader().getId();
                }
                DeparmentDTO deparmentDTO = new DeparmentDTO(department.getTotalName(), department.getId() + "", learderId + "",department.getType());
                comboData.add(deparmentDTO);
            }
            return JsonResponse.successResponseWithData(comboData);
        }
        List<Department> departmentList = new ArrayList<>();
        List<Department> departments = getDeparmentUserService.getFirstDepartments();
        for (Department department : departments) {
            departmentList.add(department);
            getChildren(department, departmentList);
        }

        List<DeparmentDTO> comboData = new ArrayList<>();
        for (Department department : departmentList) {
            DeparmentDTO deparmentDTO = null;
            if (null != department.getLeader()) {
                deparmentDTO = new DeparmentDTO(department.getTotalName(), department.getId() + "", department.getLeader().getId() + "",department.getType());
            } else {
                deparmentDTO = new DeparmentDTO(department.getTotalName(), department.getId() + "", "",department.getType());
//                continue;
            }
            comboData.add(deparmentDTO);
        }
        return JsonResponse.successResponseWithData(comboData);
    }

    public void getChildren(Department department, List<Department> departmentList) {
        List<Department> children = getDeparmentUserService.getChildDepartments(department.getId());
        for (Department cDepartment : children) {
            departmentList.add(cDepartment);
            getChildren(cDepartment, departmentList);
        }
    }

    @ApiOperation("部门下拉框")
    @RequestMapping(value = "/inputDepart", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse inputDepart(String str, Long id) {
        Department department = departmentRepository.findOne(id);
        String[] array = str.split(",");
        for (String s : array) {
            if (StringUtils.isNotEmpty(s)) {
                Department adddepartment = new Department();
                adddepartment.setParent(department);
                adddepartment.setName(s);
                adddepartment.setSerialNumber("VSD");
                departmentRepository.save(adddepartment);
            }
        }
        return JsonResponse.successResponse();
    }


}
